package com.cbtx.networklib.cookie

import okhttp3.Cookie
import java.io.IOException
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.io.Serializable

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/6/29 1:46 PM
 * desc   :
 */
class SerializableHttpCookie : Serializable {

    private val serialVersionUID = 6374381323722046732L

    @Transient
    private var cookie: Cookie

    @Transient
    private var clientCookie: Cookie? = null

    constructor(cookie: Cookie) {
        this.cookie = cookie
    }

    fun getCookie(): Cookie {
        var bestCookie = cookie
        if (clientCookie != null) {
            bestCookie = clientCookie!!
        }
        return bestCookie
    }

    @Throws(IOException::class)
    private fun writeObject(out: ObjectOutputStream) {
        out.writeObject(cookie.name)
        out.writeObject(cookie.value)
        out.writeLong(cookie.expiresAt)
        out.writeObject(cookie.domain)
        out.writeObject(cookie.path)
        out.writeBoolean(cookie.secure)
        out.writeBoolean(cookie.httpOnly)
        out.writeBoolean(cookie.hostOnly)
        out.writeBoolean(cookie.persistent)
    }

    @Throws(IOException::class, ClassNotFoundException::class)
    private fun readObject(ois: ObjectInputStream) {
        val name = ois.readObject() as String
        val value = ois.readObject() as String
        val expiresAt = ois.readLong()
        val domain = ois.readObject() as String
        val path = ois.readObject() as String
        val secure = ois.readBoolean()
        val httpOnly = ois.readBoolean()
        val hostOnly = ois.readBoolean()
        val persistent = ois.readBoolean()
        clientCookie = Cookie.Builder()
            .name(name)
            .value(value)
            .expiresAt(expiresAt)
            .path(path).apply {
                if (hostOnly) this.hostOnlyDomain(domain) else this.domain(domain)
            }.apply {
                if (secure) this.secure() else this
            }.apply {
                if (httpOnly) this.httpOnly() else this
            }.build()
    }
}
